using System;
using System.Web.Mvc;
using Tools.Common.Reflection;
using Webshop20.Application;

namespace Webshop20.Bindings
{
    public class Webshop20DefaultModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);

            if (propertyDescriptor.Name == ReflectAbout<RequestMessageBase>.GetProperty(x => x.Now).Name)
                ((RequestMessageBase) bindingContext.Model).Now = DateTime.Now;

            if (propertyDescriptor.Name == ReflectAbout<RequestMessageBase>.GetProperty(x => x.AnonymousVisitorId).Name)
            {
                var cookie = controllerContext.HttpContext.Request.Cookies[ReflectAbout<RequestMessageBase>.GetProperty(x => x.AnonymousVisitorId).Name];
                if (cookie != null)
                    ((RequestMessageBase) bindingContext.Model).AnonymousVisitorId =
                        new Guid(cookie.Value);
            }

            if (propertyDescriptor.Name == ReflectAbout<RequestMessageBase>.GetProperty(x => x.VisitorId).Name &&
                controllerContext.HttpContext.User.Identity.IsAuthenticated)
            {
                ((RequestMessageBase)bindingContext.Model).VisitorId =
                    int.Parse(controllerContext.HttpContext.User.Identity.Name);
            }
        }
    }
}